import React, { useEffect } from 'react';
import { connect } from 'umi';
import { Form, Button } from 'antd';
import FormCondition from '@/components/FormCondition';
import DrawerCondition from '@/components/DrawerCondition';

const WarbandForm = (props) => {
  const {
    dispatch,
    visible = {},
    onClose,
    handleCallback,
    loading,
    departmentNewList = [],
    reload,
  } = props;

  const { show = false, detail = {} } = visible;
  const { id } = detail;
  const [form] = Form.useForm();
  // 新增修改 传id修改 不传id新增
  const fetchRoleEdit = () => {
    form.validateFields().then((values) => {
      const { id } = detail;
      const { parentDepartmentId = '' } = values;
      const payload = {
        ...detail,
        ...values,
        parentDepartmentId: parentDepartmentId.toString(),
        id,
      };
      if (parentDepartmentId === id) {
        return notification.success({
          message: '温馨提示',
          description: '子级Id不可与父级Id相同',
        });
      }
      dispatch({
        type: id ? 'system/fakeUpdateDepartment' : 'system/fakeInsertDepartment',
        payload,
        callback: () => {
          onClose();
          reload();
        },
      });
    });
  };
  const filterList = (list) => {
    return list.map((item) => {
      const { departmentName: label, id: value, subDepartmentList: children } = item;
      const localItem = {
        label,
        value,
        children: children ? filterList(children) : undefined,
      };
      return localItem;
    });
  };
  const formItems = [
    {
      label: '部门名称',
      name: 'departmentName',
    },
    {
      label: '父部门id',
      name: 'parentDepartmentId',
      type: 'cascader',
      changeOnSelect: true,
      select: filterList([{ departmentName: '无', id: '0' }, ...departmentNewList]),
      rules: [{ required: false }],
    },
    {
      label: '部门排序',
      name: 'departmentOrder',
      type: 'number',
      rules: [{ required: false }],
    },
  ];

  const modalProps = {
    title: `${id ? '修改' : '新增'}`,
    visible: show,
    onClose,
    footer: (
      <Button type="primary" loading={loading} onClick={fetchRoleEdit}>
        确定
      </Button>
    ),
  };

  return (
    <DrawerCondition {...modalProps}>
      <FormCondition form={form} formItems={formItems} initialValues={detail}></FormCondition>
    </DrawerCondition>
  );
};

export default connect(({ system, loading }) => ({
  ...system,
  loading: loading.models.system,
}))(WarbandForm);
